"""
认证服务模块
提供密码加密、验证和 JWT Token 生成功能
"""
import bcrypt
from datetime import datetime, timedelta
from jose import jwt
from config.settings import settings

def hash_password(password: str) -> str:
    """
    使用 bcrypt 加密密码
    
    Args:
        password: 明文密码
        
    Returns:
        加密后的密码字符串
    """
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode(), salt).decode()

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    验证密码是否正确
    
    Args:
        plain_password: 明文密码
        hashed_password: 加密后的密码
        
    Returns:
        密码是否匹配
    """
    return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())

def create_access_token(data: dict, expires_delta: timedelta = None) -> str:
    """
    创建 JWT Access Token
    
    Args:
        data: 要编码到 Token 中的数据（通常包含 user_id, email, role 等）
        expires_delta: Token 过期时间，默认使用配置中的值
        
    Returns:
        JWT Token 字符串
    """
    to_encode = data.copy()
    now = datetime.utcnow()
    
    if expires_delta:
        expire = now + expires_delta
    else:
        expire = now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    
    to_encode.update({
        "exp": expire,
        "iat": now,
        "type": "access"
    })
    
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    return encoded_jwt

def create_refresh_token(data: dict) -> str:
    """
    创建 JWT Refresh Token（有效期更长）
    
    Args:
        data: 要编码到 Token 中的数据
        
    Returns:
        JWT Refresh Token 字符串
    """
    to_encode = data.copy()
    now = datetime.utcnow()
    expire = now + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
    
    to_encode.update({
        "exp": expire,
        "iat": now,
        "type": "refresh"
    })
    
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    return encoded_jwt

